<template>
  <!-- 安全承诺书 -->
  <div class="commitment">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >

        <!-- 左上方菜单栏 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.commitment_delete"
            @click="handleDelete">
            删 除
          </el-button>
        </template>

        <!-- 承诺书表格自定义 -->
        <template slot="cns" slot-scope="scope">
          <div class="enclosure_div">
            <a :href="downloadHead + scope.row['cns']" v-if="scope.row['cns'] !== '' && scope.row['cns'] !== undefined">
              <i class="el-icon-download"></i>下载承诺书
            </a>
            <span v-else>-</span>
          </div>
        </template>

        <!-- 承诺书表单自定义 -->
        <template slot="cnsForm">
          <div>
            <el-upload
              v-if="dialogType !== 'view'"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="cnsFileList"
              :before-upload="beforeUploadCNS"
              :on-remove="handleRemoveCNS"
              :on-success="uploadCNSSuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
            </el-upload>

            <a
              v-else
              v-for="(item, index) in cnsFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <i class="el-icon-download" style="margin-right:5px;"></i>下载承诺书（{{ item.name }}）
            </a>
          </div>
        </template>

      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  add,
  update,
  remove
} from "@/api/duty/dutiesandresponsibilities/commitment";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";

const tenantId = JSON.parse(localStorage.getItem("saber-tenantId")).content;

export default {
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 18,
        border: true,
        addBtn: true,
        index: false,
        selection: true,
        viewBtn: true,
        editBtn: true,
        delBtn: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menuWidth: 200,
        column: [
          {
            label: "年度",
            prop: "nd",
            align: "center",
            type: "select",
            dicData: [],
            rules: [{
              required: true,
              message: "请选择年度",
              trigger: "change"
            }]
          },
          {
            label: "岗位名称",
            prop: "postId",
            search: true,
            align: "center",
            type: "select",
            dicUrl: "/api/blade-system/post/select?tenantId=" + tenantId,
            props: {
              label: "postName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择岗位",
              trigger: "change"
            }]
          },
          {
            label: "姓名",
            prop: "user",
            align: "center",
            value: JSON.parse(localStorage.getItem("saber-userInfo")).content.nick_name,
            rules: [{
              required: true,
              message: "请输入姓名",
              trigger: "blur"
            }]
          },
          {
            label: "电话",
            prop: "phone",
            align: "center"
          },
          {
            label: "承诺事项",
            prop: "cnsx",
            hide: true,
            span: 24,
            type: "textarea",
            maxLength: 150
          },
          {
            label: "承诺书",
            prop: "cns",
            align: "center",
            span: 24,
            slot: true,
            formslot: true,
            rules: [{
              required: true,
              message: "请选择承诺书",
              trigger: "blur"
            }]
          },
          {
            label: "上传时间",
            prop: "createTime",
            align: "center",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            display: false
          }
        ]
      },
      // 附件
      dialogType: "",
      downloadHead: "/api/fileManager/download/",
      SetHeaders: { "Blade-Auth": getToken() },
      cnsFileList: [],
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.commitment_add, false),
        viewBtn: this.vaildData(this.permission.commitment_view, false),
        delBtn: this.vaildData(this.permission.commitment_delete, false),
        editBtn: this.vaildData(this.permission.commitment_edit, false)
      };
    },

    // 勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {

    // 新增
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },

    // 修改
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开查看、新增、编辑弹窗前
    beforeOpen(done, type) {
      var nextYear = new Date().getFullYear() + 1;
      var yearArr = [];
      for(let i = 0 ; i < 5 ; i++) {
        yearArr.push({
          label: nextYear - i,
          value: nextYear - i
        });
      };
      var ndColumn = this.findObject(this.option.column, "nd");
      this.dialogType = type;
      ndColumn.dicData = yearArr;
      this.cnsFileList = [];
      if (["edit", "view"].includes(type)) {
        if (this.form.cns && this.form.bladeFiles && JSON.stringify(this.form.bladeFiles) !== "{}") {
          this.cnsFileList.push({
            name: this.form.bladeFiles.fileName,
            response: {
              code: 200,
              msg: "操作成功",
              success: true,
              data: this.form.bladeFiles
            }
          });
        }
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 加载数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    /**
     * 上传承诺书
     */

    // 上传承诺书前
    beforeUploadCNS(file) {
      console.log(file);
      var isLimit = this.cnsFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个承诺书!");
      }
      return isLimit;
    },

    // 上传承诺书成功
    uploadCNSSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.cnsFileList = fileList;
      this.form.cns = response.data.id;
    },

    // 删除承诺书
    handleRemoveCNS(file, fileList) {
      this.cnsFileList = fileList;
      this.form.cns = "";
    }
  }
};
</script>

<style lang="scss" scpoed>
.commitment{
  .enclosure_div {
    a {
      font-size: 12px;
      color: #409eff;

      p {
        margin-top: 0px;
        margin-bottom: 0px;
      }

      i {
        margin-right: 5px;
      }
    }
  }
}
</style>